package dog.weatherwallpaper.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import dog.weatherwallpaper.utils.App;
import dog.weatherwallpaper.utils.Strings;
import dog.weatherwallpaper.utils.Time;

public final class Weather {
	private CurrentWeather current = new CurrentWeather(null);
	private List<FutureWeather> days = Collections.nCopies(5, new FutureWeather(null));

	Weather(String json) {
		if (Strings.isNullOrEmpty(json)) { return; }
		try {
			JSONObject data = new JSONObject(json).optJSONObject("data");
			JSONObject now = data.optJSONArray("current_condition").optJSONObject(0);
			JSONArray future = data.optJSONArray("weather");

			CurrentWeather current = new CurrentWeather(now);
			List<FutureWeather> days = new ArrayList<FutureWeather>();
			for (int i = 0; i < future.length(); i++) {
				JSONObject day = future.optJSONObject(i);
				days.add(new FutureWeather(day));
			}

			this.current = current;
			this.days = days;
		} catch (Exception e) {
			App.sendMail(e);
		}
	}

	boolean isOldInfo(final int hours) {
		Time t = new Time();
		Date date = t.formatDateTime(this.days.get(0).getDate(), this.current.getTime());
		return t.isOlderThan(date, hours);
	}

	public CurrentWeather getCurrent() {
		return current;
	}

	public FutureWeather getDay(final int pos) {
		if (pos < days.size()) {
			return days.get(pos);
		} else {
			return new FutureWeather(null);
		}
	}

	/**
	 * Returns minimum temperature difference between today and tomorrow in celsius.
	 */
	public int getTempMinCVariation() {
		return days.get(0).getTempMinC() - days.get(1).getTempMinC();
	}

	/**
	 * Returns maximum temperature variation between tomorrow and today in celsius.
	 */
	public int getTempMaxCVariation() {
		return days.get(1).getTempMaxC() - days.get(0).getTempMaxC();
	}

	/**
	 * Returns minimum temperature difference between today and tomorrow in fahrenheit.
	 */
	public int getTempMinFVariation() {
		return days.get(0).getTempMinF() - days.get(1).getTempMinF();
	}

	/**
	 * Returns maximum temperature variation between tomorrow and today in fahrenheit.
	 */
	public int getTempMaxFVariation() {
		return days.get(1).getTempMaxF() - days.get(0).getTempMaxF();
	}

	public AbstractWeather tomorrow() {
		return days.get(1);
	}
}